package com.xiaomi.shwx.common.statemachine;

import com.xiaomi.shwx.common.enums.WorkOrderEvents;
import com.xiaomi.shwx.common.enums.WorkOrderStatus;
import com.xiaomi.shwx.entity.pojo.WorkOrder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * author: lei
 * description: 状态机使用
 */
@Slf4j
@Component
public class WorkOrderProcessor {

    @Resource
    private StateMachine<WorkOrderStatus, WorkOrderEvents> workOrderStateMachine;

    public boolean process(WorkOrder workOrder, WorkOrderEvents workOrderEvents) {

        Message<WorkOrderEvents> message = MessageBuilder.withPayload(workOrderEvents).setHeader("workOrder",workOrder).build();
        boolean flag = sendEvent(message);
        return flag;
    }

    @SneakyThrows
    private boolean sendEvent(Message<WorkOrderEvents> message) {
        WorkOrder workOrder = (WorkOrder) message.getHeaders().get("workOrder");
        workOrderStateMachine.start();
        boolean result = workOrderStateMachine.sendEvent(message);
        return result;
    }

}
